/*
 * @Description:
 * @Author: Zzt
 * @Date: 2022-12-28 10:01:11
 * @LastEditTime: 2023-01-16 13:53:15
 */
import { createContext, useReducer, useEffect, useContext } from 'react';
import {
  SELECT_CHANGE,
  M_SELECT_KEY,
  SET_SELECT_FOND,
  SET_SELECT_AT,
  SET_FIRST_AT,
  ADD_LIST_ITEM,
  EDIT_LIST_ITEM,
  SET_TOP_LIST,
  SET_DOWN_LIST,
  DELETE_ELIST_ITEM,
  DELETE_LIST_ITEM,
  ADD_ELIST_ITEM
} from '../constants';
import { ArchiveCollectionReducer } from '../reducers/ArchiveCollectionReducer';
import { fetchATListByFondId, ATListByFondId } from '@/api/archivesType';
import {
  addArchiveItem,
  editArchiveItem,
  fetchArchivesLevelWithPage,
  deleteERecords,
  deleteArchiveItem,
  fetchERecords,
  fetchDownLevelList
} from '@/api/archives/archives';
import { message, Modal } from 'antd';
import { fromPairs } from 'lodash-es';

const initialState = {
  // 当前选中的项目
  selectFond: {},
  selectAT: {},

  recordsData: {},
  eRecordsData: {},
  // 本层级相关信息
  baseInfo: {},
  // 上级条目信息
  upperInfo: {},
  // 选中条目向外数据方法
  selectChange: null,
  mSelectKey: [],
  batchData: {}
};
const ArchiveCollectionContext = createContext();
const ArchiveCollectionContextProvider = (props) => {
  const [state, dispatch] = useReducer(ArchiveCollectionReducer, initialState);
  const actions = {
    /**
     * @description: 设置选中全宗
     */
    setSelectFond(data) {
      dispatch({ type: SET_SELECT_FOND, data });
    },

    /**
     * @description: 设置选中的档案类型
     */
    setSelectAT(data) {
      dispatch({ type: SET_SELECT_AT, data });
    },

    getArchiveTypeList(id) {
      // ATListByFondId(id).then((res) => {
      //   const data = res.data;
      //   dispatch({ type: SET_FIRST_AT, data });
      // });
      fetchATListByFondId(id, 2).then((res) => {
        const data = res.data;
        dispatch({ type: SET_FIRST_AT, data });
      });
    },

    getTopLevelList(params) {
      return new Promise((resolve, reject) => {
        fetchArchivesLevelWithPage(params)
          .then((res) => {
            const data = res.data;
            dispatch({ type: SET_TOP_LIST, data: data.results });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },
    getERecords(params) {
      return new Promise((resolve, reject) => {
        fetchERecords(params)
          .then((res) => {
            const data = res.data;
            dispatch({ type: SET_DOWN_LIST, data: data.results });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },
    SelectChange(data) {
      dispatch({ type: SELECT_CHANGE, data });
    },

    /* 档案征集多选项 */
    setMSelectKey(data) {
      dispatch({ type: M_SELECT_KEY, data });
    },

    // 文件级操作
    /**
     * @description: 增加列表条目
     * @param {any} params 接口参数
     */
    addCollectItemFunc(params) {
      return new Promise((resolve) => {
        addArchiveItem(params).then((res) => {
          const { data } = res;
          console.log('state.recordsData.data', data);

          message.success('添加成功');
          dispatch({ type: ADD_LIST_ITEM, data: data.data });
          resolve(data);
        });
      });
    },
    /**
     * @description: 通用 - 增加列表条目
     * @param {*} data 添加的条目
     */
    addTableItem(data) {
      dispatch({ type: ADD_ELIST_ITEM, data });
    },
    delTableItem(data) {
      dispatch({ type: DELETE_ELIST_ITEM, ids: data });
    },
    /**
     * @description: 编辑列表条目
     * @param {number} id 修改的id
     * @param {any} params 接口参数
     * @param {any} orgData
     */
    editArchiveItemFunc(id, params, orgData) {
      return new Promise((resolve) => {
        editArchiveItem(params).then((res) => {
          const { data } = res;
          const editData = fromPairs(data.map((item) => [item.fieldName, item.fieldValue]));
          message.success('编辑');
          dispatch({ type: EDIT_LIST_ITEM, data: { ...orgData, ...editData }, id });
          resolve(data);
        });
      });
    },
    /**
     * @description: 删除列表条目
     * @param {*} level 层级
     * @param {*} query 请求参数
     * @param {*} content 提示内容
     * @return {*}
     */
    deleteItem(level, query, content = '确认删除选中的条目？') {
      Modal.confirm({
        title: '删除',
        content,
        onOk() {
          if (level === 0) {
            deleteERecords(query).then((res) => {
              message.success('删除成功');
              const data = res.data.map((id) => parseInt(id, 10));
              dispatch({ type: DELETE_ELIST_ITEM, ids: data });
            });
          } else {
            deleteArchiveItem(query).then((res) => {
              const data = res.data.map((id) => parseInt(id, 10));
              dispatch({ type: DELETE_LIST_ITEM, ids: data });
              message.success('删除成功');
            });
          }
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    }
  };

  useEffect(() => {
    if (state.selectFond?.id) {
      actions.getArchiveTypeList(state.selectFond.id);
      // actions.getArchiveTypeList({ id: 107 });
    }
  }, [state.selectFond]);

  return (
    <ArchiveCollectionContext.Provider value={{ ...state, ...actions }}>
      {props.children}
    </ArchiveCollectionContext.Provider>
  );
};

export const useArchiveCollectionContext = () => {
  return useContext(ArchiveCollectionContext);
};

export { ArchiveCollectionContext, ArchiveCollectionContextProvider };
